<template>
	<view class="page-container">
		<!-- 传递动态样式给子组件 -->
		<ServiceCategory :current-tab="currentTab" @tab-change="handleTabChange" :show-category="currentTab !== 1"
			:nav-bar-style="currentTab === 1 ? { backgroundColor: '#fff' } : {}" :is-tab-transparent="currentTab === 1"
			@callParent="handleCategoryChange" />

		<!-- 商铺Tab内容 -->
		<template v-if="currentTab === 0">
			<z-paging ref="pagingRef" v-if="firstLoaded || isCurrentPage" v-model="currentPaging.dataList"
				@query="fetchCurrentCategoryData" @refresh="handleRefresh"
				:fixed="false"
				:empty-config="{tip: '暂无数据'}"
				class="paging-container"
				:page-size="10"
				:auto-load="false"
				>
				<view class="content">
					<view class="item-list">
						<view class="item" v-for="(item, index) in currentPaging.dataList" :key="item.id || index"
							@click="itemClick(item)">
							<view class="shop-top">
								<image class="shop-photo" v-if="item?.merImagesList" :src="item.merImagesList[0]"
									mode="aspectFill" />
								<view class="distance-tag">
									<text class="distance-text">{{ item.distance?.toFixed(1) || '0.0' }}km</text>
								</view>
							</view>
							<view class="shop-name">
								<text class="name-text">{{ item.merName || '--' }}</text>
							</view>
						</view>
					</view>
				</view>

				<template #empty>
					<view class="empty-view">
						<text class="empty-text">暂无数据</text>
					</view>
				</template>
			</z-paging>
		</template>

		<!-- 师傅Tab内容 -->
		<template v-if="currentTab === 1">
			<view class="master-container">
				<nearMaster />
			</view>
		</template>

		<!-- 视频Tab内容 -->
		<template v-if="currentTab === 2">
			<view class="video-content">视频列表内容</view>
		</template>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		nextTick,
		computed,
		onBeforeUnmount
	} from "vue";
	import {
		onShow,
		onLoad,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		getMerchantList
	} from '@/api/near.js';
	import {
		getLatitude,
		getLongitude,
		getAreaid
	} from "@/common/util.js";
	import ServiceCategory from "./ServiceCategory.vue";
	import nearMaster from './nearMaster.vue';

	const pagingRef = ref(null);
	const firstLoaded = ref(false);
	const isCurrentPage = ref(true);
	const currentTab = ref(0);
	const isRefreshing = ref(false); // 新增：标记是否正在下拉刷新

	// 分类分页状态存储
	const categoryPagingStore = ref({
		'': {
			pageNum: 1,
			dataList: [],
			total: 0
		}
	});

	const activeCategoryId = ref('');

	// 计算属性：获取当前分类的分页数据
	const currentPaging = computed(() => {
		if (!categoryPagingStore.value[activeCategoryId.value]) {
			categoryPagingStore.value[activeCategoryId.value] = {
				pageNum: 1,
				dataList: [],
				total: 0
			};
		}
		return categoryPagingStore.value[activeCategoryId.value];
	});

	onLoad(() => {
		resetAllCategoryPaging();
		activeCategoryId.value = '';
		currentTab.value = 0;
	});

	onShow(() => {
		if (currentTab.value === 0) {
			nextTick().then(() => {
				resetAndReloadCurrentCategory();
			});
		}
	});

	onUnload(() => {
		resetAllCategoryPaging();
		activeCategoryId.value = '';
	});

	// 新增：处理下拉刷新事件
	const handleRefresh = () => {
		isRefreshing.value = true; // 标记正在刷新
		resetAndReloadCurrentCategory();
	};

	// Tab切换处理
	const handleTabChange = async (index) => {
		currentTab.value = index;
		isCurrentPage.value = index === 0;

		if (index === 0) {
			await nextTick();
			resetAndReloadCurrentCategory();
		}
	};

	// 分类切换事件
	const handleCategoryChange = (_, __, dictValue) => {
		activeCategoryId.value = dictValue || '';
		resetAndReloadCurrentCategory();
	};

	// 重置所有分类的分页状态
	const resetAllCategoryPaging = () => {
		categoryPagingStore.value = {
			'': {
				pageNum: 1,
				dataList: [],
				total: 0
			}
		};
	};

	// 重置当前分类的分页状态，并重新加载第一页
	const resetAndReloadCurrentCategory = async () => {
		if (!pagingRef.value) return;

		// 重置当前分类的页码和数据
		currentPaging.value.pageNum = 1;
		currentPaging.value.dataList = [];
		currentPaging.value.total = 0;

		await nextTick();

		// 如果是下拉刷新，使用reload方法，否则检查是否需要手动触发加载
		if (isRefreshing.value) {
			pagingRef.value.reload();
		} else if (currentPaging.value.dataList.length === 0) {
			pagingRef.value.reload();
		}

		firstLoaded.value = true;
	};

	// 加载当前分类数据
	const fetchCurrentCategoryData = async (pageNo, pageSize = 10) => {
		// 使用z-paging传递的pageNo参数，而不是使用内部存储的pageNum
		const pageNum = isRefreshing.value ? 1 : pageNo;
		const dictValue = activeCategoryId.value;

		try {
			const params = {
				type: dictValue,
				lng: getLongitude(),
				lat: getLatitude(),
				areaCode: getAreaid(),
				pageNum: pageNum,
				pageSize: pageSize
			};

			const res = await getMerchantList(params);
			const listData = Array.isArray(res) ? res : (res.rows || []);
			const total = res.total || listData.length;

			// 更新当前分类的分页数据
			if (pageNum === 1) {
				currentPaging.value.dataList = listData;
			} else {
				currentPaging.value.dataList = [...currentPaging.value.dataList, ...listData];
			}

			// 更新当前分类的页码和总数
			currentPaging.value.pageNum = pageNum + 1;
			currentPaging.value.total = total;

			// 通知z-paging加载完成
			pagingRef.value.complete(listData, total);
			firstLoaded.value = true;

			// 重置刷新状态
			isRefreshing.value = false;

		} catch (error) {
			console.error('获取商家列表失败:', error);
			pagingRef.value.complete(false);
			isRefreshing.value = false; // 出错时也要重置刷新状态
			uni.showToast({
				title: '数据加载失败',
				icon: 'none'
			});
		}
	};

	// 商铺item点击事件
	const itemClick = (item) => {
		console.log('点击的item数据:', item);
		uni.navigateTo({
			url: `/pages/nearby/nearDetails?item=${encodeURIComponent(JSON.stringify(item))}`
		});
	};

	onBeforeUnmount(() => {
		resetAllCategoryPaging();
	});
</script>

<style lang="scss" scoped>
	/* 样式保持不变 */
	.page-container {
		width: 100%;
		height: 100vh;
		background: #F5F5F5;
		box-sizing: border-box;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		position: relative;
	}

	.master-container {
		flex-grow: 1;
		overflow-y: auto;
		box-sizing: border-box;
	}

	.paging-container {
		width: 100%;
		height: calc(100vh - 120rpx);
		overflow-y: auto;
		-webkit-overflow-scrolling: touch;
		flex-grow: 1;
	}

	.content {
		padding: 20rpx;
		box-sizing: border-box;
		width: 100%;
	}

	.item-list {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		width: 100%;
		box-sizing: border-box;
		padding-bottom: env(safe-area-inset-bottom);

		.item {
			width: calc(50% - 10rpx);
			background-color: #ffffff;
			border-radius: 20rpx;
			overflow: hidden;
			margin-bottom: 20rpx;
			box-sizing: border-box;

			.shop-top {
				position: relative;
				width: 100%;
				height: 280rpx;
				background-color: #eee;

				.shop-photo {
					width: 100%;
					height: 100%;
					display: block;
				}

				.distance-tag {
					position: absolute;
					top: 16rpx;
					right: 16rpx;
					background: rgba(0, 0, 0, 0.5);
					color: #fff;
					font-size: 24rpx;
					padding: 6rpx 20rpx;
					border-radius: 21rpx;
					z-index: 2;
					font-weight: 400;
				}
			}

			.shop-name {
				padding: 30rpx 20rpx;

				.name-text {
					font-size: 30rpx;
					color: #333;
					font-weight: 500;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					overflow: hidden;
					text-overflow: ellipsis;
				}
			}
		}
	}

	.empty-view {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 100rpx;

		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}

	.video-content {
		flex-grow: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #666;
		font-size: 28rpx;
	}
</style>